package mealhistory;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;

import com.example.storage.MainActivity;
import com.example.storage.Mealdatabase;
import com.example.storage.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.ArrayList;
import java.util.List;

import Breakfast.Breakfast;
import Dinner.Dinner;
import Dinner.DinnerAdapter;
import Lunch.Lunch;
import cn.pedant.SweetAlert.SweetAlertDialog;

public class MealHistory extends AppCompatActivity {

    private Mealdatabase mealdatabase;
    private MealExpandableAdapter adapter;
    private ExpandableListView expandableListView;
    private List<MealGroup> mealGroups;
    private BottomNavigationView bottomNavigationView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(0,0);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meal_history);
        expandableListView = findViewById(R.id.expandableListView);

        mealdatabase = new Mealdatabase(this, "MEALSTORE.db", null, 3);//创建数据库
        //this.deleteDatabase("MEALSTORE.db");

        show_navigate();

        prepareMealData();
        adapter = new MealExpandableAdapter(this, mealGroups);
        expandableListView.setAdapter(adapter);

        expandableListView.setOnItemLongClickListener(new ExpandableListView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                long packedPosition = expandableListView.getExpandableListPosition(position);
                int itemType = ExpandableListView.getPackedPositionType(packedPosition);
                int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
                int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);

                if (itemType == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
                    // 显示确认对话框
                    showConfirmationDialog(groupPosition, childPosition);
                    return true; // 指示长按事件已被处理
                }
                return false;
            }
        });


    }

    @Override
    protected void onResume() {
        overridePendingTransition(0,0);
        super.onResume();
        show_navigate();
    }

    private void show_navigate(){
        bottomNavigationView = findViewById(R.id.navigation);
        bottomNavigationView.setSelectedItemId(R.id.nav_history);

        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            int id = item.getItemId();
            if (id == R.id.nav_main) {
                startActivity(new Intent(this, MainActivity.class));
                return true;
            } else if (id == R.id.nav_breakfast) {
                startActivity(new Intent(this, Breakfast.class));
                return true;
            } else if (id == R.id.nav_lunch) {
                startActivity(new Intent(this, Lunch.class));
                return true;
            } else if (id == R.id.nav_dinner) {
                startActivity(new Intent(this, Dinner.class));
                return true;
            } else if (id == R.id.nav_history) {
                return true;
            }
            return false;
        });
    }

    private void prepareMealData() {
        mealGroups = new ArrayList<>();
        Cursor cursor = mealdatabase.getDistinctDateType();
        if (cursor != null) {
            try {
                int dateIndex = cursor.getColumnIndex("date");
                int typeIndex = cursor.getColumnIndex("type");

                if (dateIndex != -1 && typeIndex != -1) { // 确保找到所需的列
                    while (cursor.moveToNext()) {
                        String date = cursor.getString(dateIndex);
                        String type = cursor.getString(typeIndex);

                        // 使用date和type获取对应的Meal数据
                        Cursor mealCursor = mealdatabase.getMealDataByDateAndType(date, type);
                        List<Mealitem> mealItems = new ArrayList<>();
                        if (mealCursor != null) {
                            try {
                                int foodIndex = mealCursor.getColumnIndex("food");
                                int weightIndex = mealCursor.getColumnIndex("weight");
                                int consumptionIndex = mealCursor.getColumnIndex("consumption");
                                int idIndex=mealCursor.getColumnIndex("id");

                                // 检查是否所有必要的列索引都有效
                                if (foodIndex != -1 && weightIndex != -1 && consumptionIndex != -1 && idIndex != -1) {
                                    while (mealCursor.moveToNext()) {
                                        String food = mealCursor.getString(foodIndex);
                                        int weight = mealCursor.getInt(weightIndex);
                                        double consumption = mealCursor.getDouble(consumptionIndex);
                                        int id=mealCursor.getInt(idIndex);

                                        // 创建Mealitem对象并加入列表
                                        mealItems.add(new Mealitem(id, food, weight, consumption, date, type));
                                    }
                                }
                            } finally {
                                mealCursor.close(); // 确保Cursor被关闭
                            }
                        }
                        mealGroups.add(new MealGroup(date, type, mealItems)); // 创建MealGroup并添加到列表
                    }
                }
            } finally {
                cursor.close(); // 确保外层Cursor也被关闭
            }
        } else {
            // 处理Cursor为null的情况
        }
    }

    public void removeGroupOrChild(int groupPosition, int childPosition) {
        // 获取对应的 Mealitem
        Mealitem itemToRemove = mealGroups.get(groupPosition).getMeals().get(childPosition);

        // 从数据库中删除
        mealdatabase.deleteMealItem(itemToRemove.getId());

        // 从数据模型中删除
        List<Mealitem> childList = mealGroups.get(groupPosition).getMeals();
        if (childList != null) {
            childList.remove(childPosition);
            adapter.notifyDataSetChanged(); // 通知适配器数据已改变
        }
    }

    private void showConfirmationDialog(int groupPosition, int childPosition) {
        new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("确定删除?")
                .setContentText("删除该项记录")
                .setConfirmText("确定")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        removeGroupOrChild(groupPosition, childPosition);
                        sDialog
                                .setTitleText("删除!")
                                .setContentText("该项记录已被删除!")
                                .setConfirmText("好的")
                                .setConfirmClickListener(null)
                                .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                    }
                })
                .setCancelButton("取消", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismissWithAnimation();
                    }
                })
                .show();
    }
}